import yaml
from pydantic import BaseModel
from typing import Optional, Any
from pathlib import Path
from core.config.config import Config  # Import the config function


class _CfgProxy:
    _val: Optional[Config] = None

    def __getattr__(self, name: str) -> Any:
        if self._val is None:
            raise RuntimeError("cfg 未初始化：请先调用 init_cfg(config_path)")
        return getattr(self._val, name)


cfg = _CfgProxy()


def init_config(cfg_path: str):
    global _cfg
    path = Path(cfg_path)
    if not path.exists():
        raise FileNotFoundError(f"Config file not found: {cfg_path}")
    with path.open("r", encoding="utf-8") as f:
        data = yaml.safe_load(f)
    cfg._val = Config(**data)
